package cn.petplatform.petback.service.publishpets.impl;

import cn.petplatform.dto.ResponseDto;
import cn.petplatform.petback.exceptions.DataTransformException;
import cn.petplatform.petback.exceptions.PublishPetException;
import cn.petplatform.petback.mapper.PetMapper;
import cn.petplatform.petback.mapper.PetPublishMapper;
import cn.petplatform.petback.mapper.PublishPetDetailInfoMapper;
import cn.petplatform.petback.pojo.Pet;
import cn.petplatform.petback.pojo.PetPublish;
import cn.petplatform.petback.pojo.vo.AdoptInfoVo;
import cn.petplatform.petback.pojo.vo.PublishPetDetailVo;
import cn.petplatform.petback.service.publishpets.PublishPetsService;
import cn.petplatform.utils.JWTUtils;
import cn.petplatform.utils.ProcessFileUtils;
import cn.petplatform.utils.UUIDUtils;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

/**
 * @author LNL
 * @date 2021/5/15 16:35
 */
@Service("publishPetsService")
@Transactional
public class PublishPetsServiceImpl implements PublishPetsService {

    private static final String FILE_ROOT_PATH = "/static/upload";

    //Autowired：自动注入
    @Autowired
    private PublishPetDetailInfoMapper publishPetDetailInfoMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private PetPublishMapper petPublishMapper;


    @Override
    public ResponseDto getAllPublishPets() {
        ResponseDto responseDto = null;
        List<PublishPetDetailVo> detailVos = publishPetDetailInfoMapper.getAllPublishPets();

        Optional<List<PublishPetDetailVo>> optionalList = Optional.ofNullable(detailVos);
        if (optionalList.isPresent()) {//如果不为空
            responseDto = new ResponseDto("1000", "最新发布宠物信息", detailVos);
        } else {
            throw new DataTransformException("数据异常，请联系管理员");
        }
        return responseDto;
    }

    @Override
    public ResponseDto insertPublishPet(MultipartHttpServletRequest request) {
        ResponseDto responseDto = null;
        //逻辑: 先添加宠物信息，再添加宠物发布信息,处理文件上传,上传的必须是图片类型，前端进行判定
        Map<String, String> fileData = ProcessFileUtils.processFile(request);
        try {
            if (fileData.size() > 0) {
                //获取token中的数据
                DecodedJWT userInfo = JWTUtils.getUserInfo(request.getHeader("token"));
                String userId = userInfo.getClaim("userId").asString();
                //普通属性有：nickname、petTypeId、introduce、adoptAddress、age、phone、email、sex、title
                //map中包含了以上多个普通属性
                Map<String, String[]> parameterMap = request.getParameterMap();
                Pet pet = new Pet();
                pet.setId(UUIDUtils.getUUID());
                pet.setNickname(parameterMap.get("nickname")[0] == null ? "" : parameterMap.get("nickname")[0]);
                pet.setPetTypeId(parameterMap.get("petTypeId")[0] == null ? "" : parameterMap.get("petTypeId")[0]);
                pet.setIntroduce(parameterMap.get("introduce")[0] == null ? "" : parameterMap.get("introduce")[0]);
                pet.setAdoptAddress(parameterMap.get("adoptAddress")[0] == null ? "" : parameterMap.get("adoptAddress")[0]);
                pet.setPicturePath(fileData.get("filePath"));
                pet.setAge(Integer.valueOf(parameterMap.get("age")[0]) == null ? 0 : Integer.valueOf(parameterMap.get("age")[0]));
                pet.setPhone(parameterMap.get("phone")[0] == null ? "" : parameterMap.get("phone")[0]);
                pet.setEmail(parameterMap.get("email")[0] == null ? "" : parameterMap.get("phone")[0]);
                pet.setSex(Integer.valueOf(parameterMap.get("sex")[0]) == null ? -1 : Integer.valueOf(parameterMap.get("sex")[0]));
                pet.setCreateTime(new Date());
                pet.setCreateUser(userId);
                pet.setIsAdopt(0);
                pet.setCareCount(0);

                //发布消息的数据封装
                PetPublish petPublish = new PetPublish();
                petPublish.setId(UUIDUtils.getUUID());
                petPublish.setTime(new Date());
                petPublish.setCareCount(0);
                petPublish.setIsPass(0);
                petPublish.setTitle(parameterMap.get("title")[0] == null ? "" : parameterMap.get("title")[0]);
                petPublish.setPetId(pet.getId());
                petPublish.setUserId(userId);
                petPublish.setCreateUser(userId);
                petPublish.setCreateTime(new Date());
                //发布操作
                int isInsertPet = petMapper.insertSelective(pet);
                int isPublish = petPublishMapper.insertSelective(petPublish);
                //操作成功
                if (isInsertPet > 0 && isPublish > 0) {
                    //将宠物的id存放到session中
                    responseDto = new ResponseDto("1000", "宠物发布成功,等待管理员审核！");
                } else {
                    throw new PublishPetException("宠物发布失败");
                }
            } else {
                ProcessFileUtils.failDeleteFile(fileData.get("filePath"));
                throw new PublishPetException("宠物图片上传失败");
            }
        } catch (Exception e) {
            //如果到这里来，说明上传失败,将刚保存的文件删除
            ProcessFileUtils.failDeleteFile(fileData.get("filePath"));
            throw new PublishPetException("宠物发布失败");
        }
        return responseDto;
    }

    @Override
    public ResponseDto deletePublishPet(String id) {
        ResponseDto responseDto = null;
        int isDelete = petPublishMapper.deleteByPrimaryKey(id);

        if(isDelete > 0) {
            responseDto = new ResponseDto("1000","删除成功");
        }else {
            responseDto = new ResponseDto("1001","删除失败");
        }
        return responseDto;
    }

    @Override
    public ResponseDto getPublishPetsByPerson(String id) {
        ResponseDto responseDto = null;
        if(id == null || "".equals(id)) {
            throw new RuntimeException("id不能为空");
        }
        List<PublishPetDetailVo> adoptPets = publishPetDetailInfoMapper.getPublishPetsByPerson(id);
        Optional<List<PublishPetDetailVo>> optionalList = Optional.ofNullable(adoptPets);
        if(optionalList.isPresent()) {//如果不为空
            responseDto = new ResponseDto("1000","个人发布宠物",adoptPets);
        }else {
            throw new DataTransformException("数据异常，请联系管理员");
        }
        return responseDto;
    }

    @Override
    public ResponseDto getAllPublishes() {
        ResponseDto responseDto = null;
        List<PublishPetDetailVo> detailVos = publishPetDetailInfoMapper.getAllPublishes();
        Optional<List<PublishPetDetailVo>> optionalList = Optional.ofNullable(detailVos);
        if (optionalList.isPresent()) {//如果不为空
            responseDto = new ResponseDto("1000", "最新发布宠物信息", detailVos);
        } else {
            throw new DataTransformException("数据异常，请联系管理员");
        }
        return responseDto;
    }

    @Override
    public ResponseDto getPublishPets(String msg) {
        ResponseDto responseDto = null;
        List<PublishPetDetailVo> adoptPets = publishPetDetailInfoMapper.getPublishPetsByMsg(msg);
        Optional<List<PublishPetDetailVo>> optionalList = Optional.ofNullable(adoptPets);
        if(optionalList.isPresent()) {//如果不为空
            responseDto = new ResponseDto("1000","领养宠物信息",adoptPets);
        }else {
            throw new DataTransformException("数据异常，请联系管理员");
        }
        return responseDto;
    }

    @Override
    public ResponseDto getDetailPet(String id) {
        ResponseDto responseDto = null;
        if(id == null || "".equals(id)) {
            throw new RuntimeException("id不能为空");
        }
        PublishPetDetailVo publishPetDetailVo = publishPetDetailInfoMapper.getDetailPet(id);
        Optional<PublishPetDetailVo> optionalList = Optional.ofNullable(publishPetDetailVo);
        if(optionalList.isPresent()) {//如果不为空
            responseDto = new ResponseDto("1000","宠物详细信息",publishPetDetailVo);
        }else {
            throw new DataTransformException("数据异常，请联系管理员");
        }
        return responseDto;
    }


}
